<template>
    <div class="calendar">
        <!-- 日历头部 -->
        <div class="calendar-header">
            <span>选择月份:</span>
            <select v-model="selectedYear" @change="updateDatesAndFetchData()">
                <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
            </select>
            <select v-model="selectedMonth" @change="updateDatesAndFetchData()">
                <option v-for="(month, index) in months" :key="index" :value="index">{{ month }}
                </option>
            </select>
        </div>

        <!-- 星期标头 -->
        <table class="weekdays-table">
            <tr>
                <th v-for="(day, index) in weekdays" :key="day"
                    :class="{ weekend: index === 5 || index === 6 }">{{ day }}</th>
            </tr>
        </table>

        <!-- 日历主体 -->
        <table class="days">
            <tr v-for="(week, weekIndex) in weeks" :key="weekIndex">
                <td v-for="(day, dayIndex) in week"
                    :key="day.date ? day.date.toISOString() : `${weekIndex}-${day.day}-empty`"
                    @click="selectDay(day)" :class="{ weekend: dayIndex === 5 || dayIndex === 6 }">
                    <div class="day-number">{{ day.day }}</div>
                    <div v-if="day.events" class="event-info" v-html="day.events"></div>
                </td>
            </tr>
        </table>

        <!-- 数据统计分析 -->
        <div class="statistics-container">
            <table class="statistics-table">
                <thead>
                    <tr>
                        <th rowspan="2">本月应上班天数</th>
                        <th rowspan="2">本月正常打卡天数</th>
                        <th colspan="3">本月异常天数</th>
                        <th colspan="3">本月加班时长</th>
                    </tr>
                    <tr>
                        <th>迟到</th>
                        <th>早退</th>
                        <th>请假</th>
                        <th>工作日</th>
                        <th>周六日</th>
                        <th>节假日</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>{{ totalPunchCount }} 天</td>
                        <td>{{ normalPunchCount }} 天</td>
                        <td>{{ latePunchCount }} 天</td>
                        <td>{{ earlyLeaveCount }} 天</td>
                        <td>{{ leaveCount }} 天</td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script>
import { getAction } from '../../../api/manage';

export default {
    props: ['admitGuid'],
    data() {
        return {
            selectedYear: new Date().getFullYear(),
            selectedMonth: new Date().getMonth(),
            weekdays: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            events: [],
            url: {
                getPersonInfo: '/clockRecord/clockRecord/getPersonInfo',
            },
            normalPunchCount: 0,
            abnormalPunchCount: 0,
            latePunchCount: 0,
            earlyLeaveCount: 0,
            leaveCount: 0,
            totalPunchCount: 0,
        };
    },
    computed: {
        years() {
            const currentYear = new Date().getFullYear();
            const startYear = currentYear - 10;
            const endYear = currentYear + 10;
            let years = [];
            for (let year = startYear; year <= endYear; year++) {
                years.push(year);
            }
            return years;
        },
        months() {
            return [
                "一月", "二月", "三月", "四月", "五月", "六月",
                "七月", "八月", "九月", "十月", "十一月", "十二月"
            ];
        },
        monthStart() {
            return new Date(this.selectedYear, this.selectedMonth, 1).toLocaleDateString('en-CA');
        },
        nextMonthStart() {
            return new Date(this.selectedYear, this.selectedMonth + 1, 1).toLocaleDateString('en-CA');
        },
        daysInMonth() {
            return new Array(new Date(this.selectedYear, this.selectedMonth + 1, 0).getDate()).fill(0).map((_, i) => i + 1);
        },
        firstDayOfMonth() {
            return (new Date(this.selectedYear, this.selectedMonth, 1).getDay() || 7);
        },
        lastDayOfMonth() {
            return (new Date(this.selectedYear, this.selectedMonth + 1, 0).getDay() || 7);
        },
        daysWithEvents() {
            let eventsByDay = {};
            this.events.forEach(event => {
                let dateString = new Date(event.date).toLocaleDateString('en-CA');
                if (!eventsByDay[dateString]) {
                    eventsByDay[dateString] = [];
                }
                let formattedEvent;
                if (event.abnormal === 1 && event.abnormal_type === 2) {
                    formattedEvent = `<div style="color: orange;">未打卡</div><span>异常信息：</span><span style="color: orange;">${event.item_text || ''}</span>`;
                } else {
                    let inTimeDisplay = event.in_time ? `上班时间：${event.in_time.split(' ')[1]}` : '上班时间：';
                    let outTimeDisplay = event.out_time ? `下班时间：${event.out_time.split(' ')[1]}` : '下班时间：';
                    formattedEvent = `${inTimeDisplay}<br>${outTimeDisplay}`;
                    if (event.abnormal === 1) {
                        formattedEvent += `<br><span>异常信息：</span><span style="color: orange;">${event.item_text || ''}</span>`;
                    }
                }
                eventsByDay[dateString].push(formattedEvent);
            });
            return eventsByDay;
        },
        weeks() {
            let days = [];

            // 上个月最后几天
            let previousMonthLastDay = new Date(this.selectedYear, this.selectedMonth, 0).getDate();
            for (let i = 0; i < this.firstDayOfMonth - 1; i++) {
                let dayNumber = previousMonthLastDay - (this.firstDayOfMonth - 1) + i + 1;
                let date = new Date(this.selectedYear, this.selectedMonth - 1, dayNumber);
                let dateString = date.toLocaleDateString('en-CA');
                let hasEvent = this.daysWithEvents[dateString] ? this.daysWithEvents[dateString].join("<br>") : '';
                days.push({ day: dayNumber, date: date, events: hasEvent });
            }

            // 当前月份所有天数
            this.daysInMonth.forEach(day => {
                let date = new Date(this.selectedYear, this.selectedMonth, day);
                let dateString = date.toLocaleDateString('en-CA');
                let hasEvent = this.daysWithEvents[dateString] ? this.daysWithEvents[dateString].join("<br>") : '';
                days.push({ day: day, date: date, events: hasEvent });
            });

            // 下个月前几天
            let remainingDaysInWeek = 7 - this.lastDayOfMonth;
            for (let i = 1; i <= remainingDaysInWeek; i++) {
                let date = new Date(this.selectedYear, this.selectedMonth + 1, i);
                let dateString = date.toLocaleDateString('en-CA');
                let hasEvent = this.daysWithEvents[dateString] ? this.daysWithEvents[dateString].join("<br>") : '';
                days.push({ day: i, date: date, events: hasEvent });
            }

            // 分割为周
            let weeks = [];
            for (let i = 0; i < days.length; i += 7) {
                weeks.push(days.slice(i, i + 7));
            }
            return weeks;
        }
    },
    mounted() {
        this.updateDatesAndFetchData();
    },
    methods: {
        selectDay(day) {
            if (day.date) {
                console.log(`Selected day: ${day.day}`);
            }
        },
        updateDatesAndFetchData() {
            this.fetchEventData();
        },
        fetchEventData() {
            const param = '?admitGuid=' + this.admitGuid + '&monthStart=' + this.monthStart + '&nextMonthStart=' + this.nextMonthStart;
            getAction(this.url.getPersonInfo + param).then((res) => {
                if (res.success) {
                    this.events = res.result;
                    this.calculateStatistics();
                } else {
                    this.$message.warning(res.message);
                }
            });
        },
        calculateStatistics() {
            this.normalPunchCount = 0;
            this.abnormalPunchCount = 0;
            this.latePunchCount = 0;
            this.earlyLeaveCount = 0;
            this.leaveCount = 0;
            this.totalPunchCount = this.events.length;

            this.events.forEach(event => {
                if (event.abnormal === 0) {
                    this.normalPunchCount++;
                } else if (event.abnormal === 1) {
                    this.abnormalPunchCount++;
                    switch (event.abnormal_type) {
                        case 3:
                            this.latePunchCount++;
                            break;
                        case 4:
                            this.earlyLeaveCount++;
                            break;
                        case 5:
                            this.leaveCount++;
                            break;
                        default:
                            break;
                    }
                }
            });
        }
    }
}
</script>

<style scoped>
.calendar {
    width: 100%;
    max-width: 90%;
    margin: auto;
    font-size: 1.2em;
}

.calendar-header {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 15px;
}

.calendar-header span {
    margin-right: 10px;
}

.calendar-header select {
    margin: 0 5px;
    padding: 5px;
}

.weekdays-table,
.days {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

.weekdays-table th,
.days td {
    width: 14.28%;
    text-align: left;
    padding: 35px;
    border: 1px solid #ddd;
    position: relative;
    vertical-align: top;
}

.day-number {
    font-size: 0.8em;
    color: #aaa;
    position: absolute;
    top: 5px;
    right: 5px;
}

.event-info {
    font-size: 0.9em;
    margin-top: 20px;
    white-space: pre-line;
}

.days td:hover {
    background-color: #f0f0f0;
}

.weekend {
    background-color: #f8f8f8;
}

.statistics-container {
    margin-top: 20px;
}

.statistics-table {
    width: 100%; /* Adjusted to full width */
    border-collapse: collapse;
    margin-top: 10px;
}

.statistics-table th,
.statistics-table td {
    padding: 10px;
    border: 1px solid #ddd;
    text-align: center; /* Center-align text */
}

.statistics-table th {
    background-color: #f2f2f2;
    font-weight: bold;
}

.statistics-table tr:nth-child(even) {
    background-color: #f9f9f9;
}
</style>



